package xyz.kail.demo.consul.client;

import com.orbitz.consul.Consul;
import com.orbitz.consul.KeyValueClient;
import com.orbitz.consul.async.ConsulResponseCallback;
import com.orbitz.consul.model.ConsulResponse;
import com.orbitz.consul.model.kv.Value;
import com.orbitz.consul.option.QueryOptions;

import java.io.IOException;
import java.math.BigInteger;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author Kail
 * @since 2018/1/16.
 */
public class WatchKvHelloMain {

    static Consul consul = Consul.newClient();

    public static void main(String[] args) throws IOException {

        KeyValueClient kvClient = consul.keyValueClient();
        kvClient.putValue("foo", "bar");
        kvClient.getValue("",QueryOptions.blockSeconds(1,null).near("").build());

        ConsulResponseCallback<Optional<Value>> callback = new ConsulResponseCallback<Optional<Value>>() {

            AtomicReference<BigInteger> index = new AtomicReference<>(null);

            @Override
            public void onComplete(ConsulResponse<Optional<Value>> consulResponse) {

                if (consulResponse.getResponse().isPresent()) {
                    Value v = consulResponse.getResponse().get();
                    System.out.println("Value is: {}" + v.getValue());
                    System.out.println("Value is: {}" + v.getValueAsString());
                }

                index.set(consulResponse.getIndex());
                watch();
            }

            void watch() {
                kvClient.getValue("foo", QueryOptions.blockMinutes(5, index.get()).build(), this);
            }

            @Override
            public void onFailure(Throwable throwable) {
                watch();
            }
        };

        kvClient.getValue("foo", QueryOptions.blockMinutes(5, new BigInteger("0")).build(), callback);

        System.in.read();

    }

}
